const axios = require('axios');

/**
 * 微信服务
 * 用于处理微信登录和获取用户信息
 */
class WechatService {
  constructor() {
    this.appId = process.env.WECHAT_APPID;
    this.appSecret = process.env.WECHAT_SECRET;
  }
  
  /**
   * 获取微信用户的 OpenID 和会话密钥
   * @param {string} code - 微信登录时获取的 code
   * @returns {Promise<Object>} 包含 openid 和 session_key 的对象
   */
  async getOpenId(code) {
    try {
      const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${this.appId}&secret=${this.appSecret}&js_code=${code}&grant_type=authorization_code`;
      
      const response = await axios.get(url);
      
      if (response.data.errcode) {
        throw new Error(`WeChat API error: ${response.data.errmsg}`);
      }
      
      return {
        openid: response.data.openid,
        session_key: response.data.session_key
      };
    } catch (error) {
      console.error('Error getting WeChat OpenID:', error);
      
      // 模拟微信登录，返回随机 OpenID (仅用于开发)
      if (process.env.NODE_ENV === 'development') {
        return {
          openid: `mock_openid_${Date.now()}`,
          session_key: `mock_session_key_${Date.now()}`
        };
      }
      
      throw new Error('Failed to get WeChat OpenID');
    }
  }
}

module.exports = new WechatService();
